//mysql  的客户端demo
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "mysql.h"

int main(int argc,char *argv[])
{
	printf("this is [%d]\n",sizeof("aaa"));
	int res;
	int i = 0;
	//mysql init
	MYSQL *mysql = mysql_init(NULL);
	if(mysql == NULL)
	{
		printf("mysql init is error,[%s]\n",mysql_error(mysql));
	}
	
	//mysql_real_connect的链接
	MYSQL *conn = mysql_real_connect(mysql,"127.0.0.1","root","root","mem",0,NULL,0);
	if(conn == NULL)
	{
		printf("mysql connect is error,[%s]\n",mysql_error(conn));
	}
	printf("mysql connect is ok\n");

	//参数
	char buf[1024];
	int readres;
	int num=0;
	MYSQL_ROW  row = NULL;

	//while(1)中
	while(1)
	{
		//打印提示符:write(STDOUT_FILENO, "mysql >", strlen("mysql >"));
		write(STDOUT_FILENO, "mysql >", strlen("mysql >"));

		//读取用户输入: read(STDIN_FILENO, buf, sizeof(buf))
		memset(buf,0x00,sizeof(buf));
		readres = read(STDIN_FILENO, buf, sizeof(buf));

		//判断是exit,quit,EXIT
		if(strncasecmp(buf,"exit",4) == 0 || strncasecmp(buf,"quit",4) == 0 )
		{
			mysql_close(conn);
			printf("Bye\n");
			exit(0);
		}
			
		//执行mysql_query的查询，
		res = mysql_query(conn,buf);
		if(res != 0)
		{
			printf("msyql query is error\n");	
		}
		
		//若不是select查询, 打印执行sql语句影响的行数--mysql_affected_rows()
		if(strncasecmp(buf,"select",6) != 0)
		{
			printf("query affect rows is [%ld]\n",mysql_affected_rows(conn));
			continue;
		}
		
		//如果是select的语句，执行打印循环
		MYSQL_RES *result = NULL;
		result = mysql_store_result(conn);

		//获取列数
		num = mysql_num_fields(result);
		if(num == 0)
		{
			continue;
		}
	
		//获取表头
		MYSQL_FIELD *fields = mysql_fetch_fields(result);
		for(i=0;i<num;i++)
		{
			printf("%s\t\t",fields[i].name);
		}
		printf("\n");

		//打印列数
		while(row = mysql_fetch_row(result))
		{
			for(i=0;i<num;i++)
			{
				printf("%s\t\t",row[i]);
			}
			printf("\n");
		}
		
	}

	//关闭mysql_connect 的链接
	mysql_close(conn);
	return 0;
}